package com.qingge.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.controller.dto.LikedCountDTO;
import com.qingge.springboot.entity.Message;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.entity.UserLike;
import com.qingge.springboot.mapper.UserLikeMapper;
import com.qingge.springboot.service.IMessageService;
import com.qingge.springboot.service.IUserLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingge.springboot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户点赞表 服务实现类
 * </p>
 *
 * @author web_work
 * @since 2023-02-18
 */
@Service
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike> implements IUserLikeService {

    @Autowired
    RedisService redisService;

    @Autowired
    IMessageService iMessageService;

    @Override
    @Transactional
    public void transLikedFromRedis2DB() {
        List<UserLike> list = redisService.getLikedDataFromRedis();
        for (UserLike like : list) {
            QueryWrapper<UserLike> userLikeQueryWrapper=new QueryWrapper<>();
            userLikeQueryWrapper.eq("liked_message_id",like.getLikedMessageId());
            userLikeQueryWrapper.eq("liked_post_id",like.getLikedPostId());
            UserLike ul = getOne(userLikeQueryWrapper);
            if (ul == null){
                //没有记录，直接存入
                save(like);
            }else if(ul.getStatus()!=like.getStatus()){
                //有记录，需要更新
                //无意间发现的bug，当数据库中有原有完全一摸一样的记录时，会报错，所以需要检测到最后状态是否一致。
                    ul.setStatus(like.getStatus());
                    save(ul);
            }
        }
    }

    @Override
    public void transLikedCountFromRedis2DB() {
        List<LikedCountDTO> list = redisService.getLikedCountFromRedis();
        for (LikedCountDTO dto : list) {
            Message message = iMessageService.getById(dto.getLikedMessageId());
            //点赞数量属于无关紧要的操作，出错无需抛异常
            if (message != null){
                Integer likeNum = message.getLikeCount() + dto.getLikeCount();//加上mysql已有点赞，redis临时点赞数
                message.setLikeCount(likeNum);
                //更新点赞数量
                iMessageService.saveOrUpdate(message);
            }
        }
    }
}
